
String generateMain(String projectName) {
  return """
import 'package:$projectName/generated/i18n.dart';
import 'package:$projectName/utils/status_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  await GetStorage.init();

  /// 禁止横屏
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

  StatusBars.setStyle('light');
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.custom;
    EasyLoading.instance.radius = 16;
    EasyLoading.instance.backgroundColor = Colors.blue;
    EasyLoading.instance.indicatorColor = Colors.white;
    EasyLoading.instance.textColor = Colors.white;

    return ScreenUtilInit(
      designSize: const Size(375, 812),
      builder: (ctx, child) {
        return GetMaterialApp(
          defaultTransition: Transition.rightToLeft,
          translations: LocalText(),
          locale: Get.deviceLocale ?? const Locale('zh'),
          fallbackLocale: const Locale('zh'),
          theme: ThemeData(
            primarySwatch: Colors.blue,
            splashFactory: NoSplash.splashFactory,
            highlightColor: Colors.transparent,
          ),
          builder: EasyLoading.init(),
          home: const MyHomePage(title: 'Flutter Demo Home Page',),
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '\$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

""";
}

String generateApiRestClient() {
  return """
import 'package:dio/dio.dart';
import 'package:retrofit/http.dart';

part 'rest_client.g.dart';

@RestApi()
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  /// 测试接口
  @GET("/testApi")
  Future<String> queryApis();

}
"""
      .trim();
}

String generateApiException() {
  return """
import 'package:dio/dio.dart';

class ApiException extends CustomDioException {
  final String code;
  final dynamic cause;
  final String? _message;

  ApiException({required this.code, String? message, this.cause})
      : _message = message;

  @override
  DioException copyWith(
      {RequestOptions? requestOptions,
      Response<dynamic>? response,
      DioExceptionType? type,
      Object? error,
      StackTrace? stackTrace,
      String? message}) {
    throw UnimplementedError();
  }

  @override
  String get message => _message ?? cause?.toString() ?? '';

  @override
  String toString() {
    var str = 'ApiException{code: \$code, message: \$message, cause: \$cause}';
    if (cause is Error) {
      str += '\\n\${(cause as Error).stackTrace}';
    }
    return str;
  }

  @override
  StackTrace get stackTrace => StackTrace.current;
}

abstract class CustomDioException implements DioException {
  static final defaultErrorRequestOptions = RequestOptions(path: '');

  @override
  String get message;

  @override
  dynamic error;

  RequestOptions _requestOptions = defaultErrorRequestOptions;

  @override
  RequestOptions get requestOptions => _requestOptions;

  set requestOptions(RequestOptions value) {
    _requestOptions = value;
  }

  @override
  Response? response;

  @override
  DioExceptionType type = DioExceptionType.unknown;
}
"""
      .trim();
}
String generateApiHttp() {
  return """
import 'package:dio/dio.dart';
import 'package:dio_http2_adapter/dio_http2_adapter.dart';
import 'package:flutter/material.dart';
import './interceptor/interceptor.dart';
import 'rest_client.dart';

class Http {

  /// 连接超时时间 30s
  static const int _connectTimeout = 15000;
  /// 接收超时时间 30s
  static const int _receiverTimeout = 30000;
  /// 发送超时时间 30s
  static const int _sendTimeout = 30000;
  
  /// 实例化
  static final Http _instance = Http._internal();

  /// 构造返回单例
  factory Http() => _instance;

  late Dio dio;
  late RestClient client;

  static late String ip;
  static late String dk;

  Http._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: "https://qa.overseasqb.com/bible-service",
      responseType: ResponseType.json,
      connectTimeout: const Duration(milliseconds: _connectTimeout),
      receiveTimeout: const Duration(milliseconds: _receiverTimeout),
      sendTimeout: const Duration(milliseconds: _sendTimeout),
    );

    dio = Dio(options);
    dio.httpClientAdapter = Http2Adapter(ConnectionManager(idleTimeout: const Duration(milliseconds: 15000)));

    /// 添加通用头部拦截器: HeaderInterceptor
    dio.interceptors.add(HeaderInterceptor());

    /// 添加日志拦截器: LogInterceptor
    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true, logPrint: (o) => debugPrint(o.toString())));

    /// 添加响应拦截器: ApiResultInterceptor
    dio.interceptors.add(ApiResultInterceptor());

    client = RestClient(dio, baseUrl: "https://qa.overseasqb.com/bible-service");
  }
}
"""
      .trim();
}

String generateApiInterceptor() {
  return """
library interceptor;

import 'dart:io';

import '../api_exception.dart';
import 'package:dio/dio.dart';

part 'header_interceptor.dart';
part 'api_result_interceptor.dart';
"""
      .trim();
}

String generateApiHeaderInterceptor() {
  return """
part of 'interceptor.dart';

class HeaderInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    options.headers["os"] = Platform.isAndroid ? 'android' : 'ios';
    options.headers["token"] = 'xxxxxx';
    
    handler.next(options);
  }
}
"""
      .trim();
}

String generateApiResultInterceptor() {
  return """
part of 'interceptor.dart';

/// 公司内部结果响应处理
/// 所有业务响应状态码: 200
/// 所有业务响应结果json字符串: code、msg、data封装
class ApiResultInterceptor extends Interceptor {

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // print("ApiResultInterceptor onResponse \${response.statusCode} \${response.data.runtimeType}");
    /// response.statusCode === 200
    final data = response.data;
    final String code = data["code"];
    final String msg = data["msg"];
    // print("ApiResultInterceptor onResponse \$code \$msg");
    if (code == "00000") {
      final Map<String, dynamic> newData = data["data"];
      response.data = newData;
      handler.next(response);
    } else {
      final apiException = ApiException(code: code, message: msg)..requestOptions = response.requestOptions;
      handler.reject(apiException, true);
    }
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err is! ApiException) {
      err = ApiException(code: "-1", message: err.message, cause: err.error);
    }
    // print("ApiResultInterceptor onError \${err.response?.statusCode} \${err.response?.data.runtimeType}");
    super.onError(err, handler);
  }
}
"""
      .trim();
}

String generateColors() {
  return """
class AppColors {
}
"""
      .trim();
}

String generateThemes() {
  return """
class AppThemes {
}
"""
      .trim();
}

String generateTrackings() {
  return """
class AppTracking {
}
"""
      .trim();
}

String generateUtilsColors() {
  return """
import 'dart:ui';

/// AUTO GENERATE BY FLUT
extension ColorExt on String {
  Color get hexColor {
    final buffer = StringBuffer();
    if (length == 6 || length == 7) buffer.write('ff');
    buffer.write(replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }
}
"""
      .trim();
}

String generateUtilsStatusBar() {
  return """
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class StatusBars {

  static void setStyle(String style) {
    // 白色沉浸式状态栏颜色  白色文字
    SystemUiOverlayStyle light = SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.black,
      systemNavigationBarDividerColor: null,

      /// 注意安卓要想实现沉浸式的状态栏 需要底部设置透明色
      statusBarColor: (Platform.isAndroid) ? Colors.transparent : null,
      systemNavigationBarIconBrightness: Brightness.light,
      statusBarIconBrightness: Brightness.light,
      statusBarBrightness: Brightness.dark,
    );

    // 黑色沉浸式状态栏颜色 黑色文字
    SystemUiOverlayStyle dark = SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.white,
      systemNavigationBarDividerColor: null,

      /// 注意安卓要想实现沉浸式的状态栏 需要底部设置透明色
      statusBarColor: (Platform.isAndroid) ? Colors.transparent : null,
      systemNavigationBarIconBrightness: Brightness.light,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Brightness.light,
    );

    'light' == style.trim()
        ? SystemChrome.setSystemUIOverlayStyle(light)
        : SystemChrome.setSystemUIOverlayStyle(dark);
  }
}
"""
      .trim();
}


String generatePubspecFlutterAssets() {
  return """

# 修改图片资源类名称为：R
flutter_assets_generator:
  class_name: R
  # 忽略这两个文件夹
  path_ignore: ["assets/font"]

"""
      .trim();
}